package com.gujiangbo.channel;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/5/3 20:48
 * @Version: 1.0
 * @Description: 使用Channel 读取文件数据
 */
public class JavaFileChannelReadDemo {

    public static void main(String[] args) throws Exception {

        RandomAccessFile file = new RandomAccessFile("/Users/gujiangbo/Desktop/project/study-nio/src/main/resources/file.txt", "rw");
        // 创建数据通道Channel
        FileChannel channel = file.getChannel();
        // 创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(48);
        // 从通道中读取缓冲数据，read方法返回值表示有多少字节被读取到buffer缓冲区中
        int bytes = channel.read(buffer);
        // 如果read方法返回 -1表示读取到文件末尾了
        while (bytes != -1) {
            System.out.println("读取:" + bytes);
            buffer.flip();
            // 查看缓冲区是否存在剩余内容
            while (buffer.hasRemaining()) {
                System.out.print((char) buffer.get());
            }
            buffer.clear();
            bytes = channel.read(buffer);
        }
        file.close();
        System.out.println("操作结束");

    }
}
